import { ajaxGet } from '@/util'

export default ({
  state: {
    areaList: [],  // 地区
    areaLoading: false
  },
  mutations: {
    setData(state, param) {
      let [key, data] = param
      data = data || []
      state[key] = data.map(item => {
        return {
          value: Number(item['id']),
          label: item['name'],
          children: (item.children || []).map(city => {
            return {
              value: Number(city.id),
              label: city.name,
              children: (city.children || []).map(area => {
                return {
                  value: Number(area.id),
                  label: area.name
                }
              })
            }
          })
        }
      })
    },
    setLoading(state, param) {
      let [key, loading] = param
      state[key] = loading
    }
  },
  actions: {
    // 请求物流数据
    getAreaList({ commit, dispatch, state }, needRefresh) {
      if (needRefresh || (!state.areaList.length && !state.areaLoading)) {
        commit('setLoading', ['areaLoading', true])
        return ajaxGet('/common/area/find_tree').then(data => {
          commit('setData', ['areaList', data])
          commit('setLoading', ['areaLoading', false])
        })
      } else {
        return state.areaList
      }
    }
  },
  getters: {
    areaList: (state) => state.areaList
  }
})
